from selenium.webdriver.support.color import Color
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec


class Base(object):
    def __init__(self, driver):
        self.driver = driver

    def open_url(self, url: str):
        try:
            if url.startswith('http://') or url.startswith('https://'):
                self.driver.get(url=url)
                self.driver.maximize_window()
                return True
            else:
                new_url = 'https://' + url
                self.driver.get(new_url)
                self.driver.maximize_window()
                return True
        except Exception as e:
            print(f"url打开失败，请检查url地址是否正确,错误:\n{e}")
            print("！" * 20)
            return False

    def set_browser_window_size(self, width, height):
        self.driver.set_window_size(width=width, height=height)
        return True

    def max_size_window(self):
        self.driver.maximize_window()
        return True

    def get_browser_window_size(self):
        return self.driver.get_window_size()

    def browser_back(self):
        self.driver.back()
        return True

    def browser_forward(self):
        self.driver.forward()
        return True

    def browser_refresh(self):
        self.driver.refresh()
        return True

    def get_cookies(self):
        cookies = self.driver.get_cookies()
        return cookies

    def del_all_cookie(self):
        self.driver.delete_all_cookies()
        return True

    def insert_cookies(self, cookies):
        for i in cookies:
            self.driver.add_cookie(i)
        return True

    def execute_js_code(self, js_code: str):
        self.driver.execute_script(js_code)
        return True

    def get_this_window(self):
        return self.driver.current_window_handle

    def get_all_window(self):
        return self.driver.window_handles

    def switch_window(self, window):
        try:
            self.driver.switch_to.window(window_name=window)
            return True
        except Exception as e:
            print(f"切换窗口失败，错误：\n{e}")
            print("!" * 40)
            return False

    def get_screenshot(self, filepath, test_case_name):
        filename = filepath + test_case_name + '.png'
        self.driver.get_screenshot_as_file(filename=filename)
        return True

    def get_element(self, locator: tuple, timeout=10):
        element = WebDriverWait(driver=self.driver, timeout=timeout).until(
            ec.presence_of_element_located(locator=locator))
        return element

    def get_elements(self, locator: tuple, timeout=10):
        elements = WebDriverWait(driver=self.driver, timeout=timeout).until(
            ec.presence_of_all_elements_located(locator=locator))
        return elements

    def click_element(self, element=None, locator=None, timeout=10):
        try:
            if element and not locator:
                element.click()
                return True
            elif locator and not element:
                self.get_element(locator=locator, timeout=timeout).click()
                return True
            else:
                print("参数传入错误，请确认参数传入限制")
                print("*" * 20)
                return True
        except Exception as e:
            print(f"元素无法点击，请确认元素是否支持点击，错误信息：\n{e}")
            print("!" * 40)
            return False

    def clear_input_box(self, element=None, locator=None, timeout=10):
        if element and not locator:
            element.clear()
            return True
        elif locator and not element:
            self.get_element(locator=locator, timeout=timeout).clear()
            return True
        else:
            print("参数传入错误，请确认参数传入限制")
            print("*" * 20)
            return False

    def send_keys(self, element=None, locator=None, timeout=10, keywords=None):
        try:
            if element and not locator:
                element.send_keys(keywords)
                return True
            elif locator and not element:
                self.get_element(locator=locator, timeout=timeout).send_keys(keywords)
                return True
            else:
                print("参数传入错误，请确认参数传入限制")
                print("*" * 20)
                return False
        except Exception as e:
            print(f"元素输入，请确认元素是否支持输入，错误信息：\n{e}")
            print("!" * 40)
            return False

    def get_element_text(self, element=None, locator=None, timeout=10):
        try:
            if element and not locator:
                return element.text
            elif locator and not element:
                return self.get_element(locator=locator, timeout=timeout).text
            else:
                print("参数传入错误，请确认参数传入限制")
                print("*" * 20)
                return False
        except Exception as e:
            print(f"无法捕获元素文本信息，错误信息：\n{e}")
            print("!" * 40)
            return False

    @staticmethod
    def get_element_attribute(attribute_name: str, element=None):
        return element.get_attribute(name=attribute_name)

    def is_message_in_element(self, message, element=None, locator=None, timeout=10):
        text = self.get_element_text(element=element, locator=locator, timeout=timeout)
        if text == message:
            return True
        else:
            return False

    def get_element_color(self, element=None, locator=None, timeout=10):
        try:
            if element and not locator:
                element_color = element.value_of_css_property('color')
                color_result = Color.from_string(element_color).hex
                return color_result
            elif locator and not element:
                element_color = self.get_element(locator=locator, timeout=timeout).value_of_css_property('color')
                color_result = Color.from_string(element_color).hex
                return color_result
            else:
                print("参数传入错误，请确认参数传入限制")
                print("*" * 20)
                return False
        except Exception as e:
            print(f"无法捕获元素颜色信息，错误信息：\n{e}")
            print("!" * 40)
            return False

    def is_color_in_element(self, color, element=None, locator=None, timeout=10):
        color_result = self.get_element_color(element=element, locator=locator, timeout=timeout)
        if color == color_result:
            return True
        else:
            return False

    def switch_to_frame(self, element):
        return self.driver.switch_to.frame(element)

    def switch_to_upper_frame(self, element):
        return self.driver.switch_to.parent_frame(element)

    def switch_to_master_document(self):
        return self.driver.switch_to.default_content()

    def switch_to_alert(self):
        return self.driver.switch_to.alert()

    def alert_accept(self):
        return self.driver.switch_to.alert.accept()

    def alert_dismiss(self):
        return self.driver.switch_to.alert.dismiss()

    def alert_text(self):
        return self.driver.switch_to.alert.text

    @staticmethod
    def get_element_location(element):
        return element.rect


if __name__ == '__main__':
    from selenium import webdriver

    driver = webdriver.Chrome()
    fe = driver.find_element()
    fe.get_attribute(name='value')
    pass
